package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;


    @Override
    public PageDTO<BrandDTO> pageQuery(Integer page, Integer rows, String key) {
        IPage<Brand> iPage = new Page<>(page, rows);
//        查询过程中参数封装在ipage对象中
//        并且返回结果也封装在ipage中 所以 查询的时候，会自动把查询结果封装回填给ipage
        //select * from tb_brand [where name like %富士% or letter = 'F'] limit 0,5
        page(iPage,new QueryWrapper<Brand>()
                .like(null!=key,"name",key)
                .or()
                .eq(null!=key,"letter",key));
//        封装成pageDTO 封装数据来自ipage
        return new PageDTO<BrandDTO>(iPage.getTotal(), iPage.getPages(),BrandDTO.convertEntityList(iPage.getRecords()));
    }

    @Override
    public BrandDTO queryBrandById(Long id) {
        return new BrandDTO(this.getById(id));
    }

    @Override
    public List<BrandDTO> listBrandByIds(List<Long> ids) {


        return BrandDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long cid) {
//        根据分类id在中间表获取到品牌的id集合
        List<Long> brandIds = this.categoryBrandService.query()
                .eq("category_id", cid)
                .list()
                .stream()
                .map(CategoryBrand::getBrandId).collect(Collectors.toList());
//        根据品牌id集合在品牌表中查对应的品牌信息
        return this.listBrandByIds(brandIds);
    }

    @Override
    @Transactional
    public void addBrand(String name,Character letter, String image, List<Long> categoryIds) {
        Brand brand = new Brand();
        brand.setName(name);
        brand.setLetter(letter);
        brand.setImage(image);
//        保存品牌信息 并且回显主键id
        this.save(brand);
//        保存中间表关系
       saveCategoryBrand(categoryIds,brand.getId());
    }

    private void saveCategoryBrand(List<Long> categoryIds, Long bid) {
        //遍历前端提交的对象id集合，构造中间表对象id的集合
        List<CategoryBrand> categoryBrands = categoryIds
                .stream()
                .map(categoryId -> CategoryBrand.of(categoryId, bid))
                .collect(Collectors.toList());
        //        for (Long categoryId : categoryIds) {
//            this.categoryBrandService.save(CategoryBrand.of(categoryId,brand.getId()));
//        }
        this.categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    public void updateBrand(Long id, String name, Character letter, String image, List<Long> categoryIds) {
        Brand brand = new Brand();
        brand.setId(id);
        brand.setName(name);
        brand.setLetter(letter);
        brand.setImage(image);
//        根据主键id进行品牌修改
        this.updateById(brand);
        //中间表处理，一次性删除所有的品牌分类的关联信息，

        //delete from tb_category_brand where brand_id = #{bid}
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",brand.getId()));

        //重建品牌和分类的关系
        saveCategoryBrand(categoryIds,id);

    }

    @Override
    @Transactional
    public void deleteBrandById(Long bid) {
        //TODO 删除一定要考虑其他位置的引用，比如说商品中引用了品牌，则不能删除

//        根据品牌id删除品牌对象
        this.removeById(bid);
//       根据品牌id删除中间表关系
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",bid));


    }
}
